<?php

namespace app\index\model;

use think\Model;

class Image extends Model
{

    public $rootUrl = null ;
    public $tmp     = 'img/' ;

    public $path    = [
        'ffmpeg.binaries'   => '/usr/local/bin/ffmpeg',
        'ffprobe.binaries'  => '/usr/local/bin/ffprobe',
        'timeout'           => 3600, // The timeout for the underlying process
        'ffmpeg.threads'    => 12,   // The number of threads that FFMpeg should use
    ];

    public $info    = [] ;

    // 入口
    public function process ($data=[]){
        
        $this->rootUrl = dirname( dirname( dirname( dirname(__FILE__) ) ) )."/public/" ;

        try {
            $this->log('---------------start------------------');
            // 转换
            $imgs   = $this->run($data);

        } catch (ValidateException $e) {
            // 这是进行验证异常捕获
            $this->log([ 'err' , $e->getError() ] );
            //return json($e->getError());
            $this->log('---------------stop------------------');
            return false ;
        } catch (\Exception $e) {
            // 这是进行异常捕获
            $this->log([ 'msg' , $e->getMessage() ] );
            //return json($e->getMessage());
            $this->log('---------------stop------------------');
            return false ;
        }
        $this->log('---------------stop------------------');
        return $imgs ;
    }

    // 转换
    public function run ($data=[]){

        $ffprobe    = \FFMpeg\FFProbe::create();
        if ( $ffprobe->isValid($data['file']) ) {
            // 视频时长
            $duration   = $ffprobe->format($data['file'])->get('duration');
            $duration   = floor( (int) $duration-1 ) ;
            // 创建对象
            $ffmpeg     = \FFMpeg\FFMpeg::create($this->path);
            // 打开资源
            $video      = $ffmpeg->open($data['file']);

            $num            = (int) $data['num'] - 1 ;
            $tot_score      = [0] ;
            $length         = $duration - 1 ;
            if ( $num>=2 ) {
                for ($i = 1 ; $i < $num ; $i++) {
                    $tot_score[$i]  = round( $length * ( $i / $num ) );
                }
            }
            if ( $num > 0  ) {
                $tot_score[]    = $length ;
            }

            print_r( $tot_score );

            $pppath = 'Uploads/' . $this->tmp . date('Ymd').'/' ;
            $ppath  = $this->rootUrl . $pppath  ;
            $this->mkdir( $pppath ) ;

            $imgs   = [] ;
            foreach ( $tot_score as $key => $value ) {
                $fileUrl    = uniqid().'.jpg' ;
                $video
                    ->frame( \FFMpeg\Coordinate\TimeCode::fromSeconds($value) )
                    ->save( $ppath.$fileUrl );
                    print_r( $ppath.$fileUrl );

                $imgs[ (string) bcadd($value,'0.0',1) ] = $pppath.$fileUrl ;
            }

            print_r( $imgs );

            // 记录信息
            $this->R();
            $md5            = $this->remd($data) ;
            $data['images'] = $imgs ;
            $this->redis->HSET('imgs',$md5,json_encode(
                $data,JSON_UNESCAPED_UNICODE
            ));

            return true ;
        }else{
            exception('文件读取失败');
        }
    }

    // 获取
    public function get_info($id=null){
        $this->R();
        $info   = $this->redis->HGET('imgs',$id);
        return json_decode($info,true);
    }

    // 设置
    public function set_info($data=null){
        $this->R();
        $md5            = $this->remd($data) ;
        $data['images'] = [] ;
        $this->redis->HSET('imgs',$md5,json_encode(
            $data,JSON_UNESCAPED_UNICODE
        ));
    }

    public $redis   = null ;
    private function R() {
        if ( ! $this->redis) {
            $this->redis = \think\facade\Cache::store('redis')->handler();
        }
        return $this->redis;
    }

    public function remd($data) {
        asort($data) ;
        $md5    = date('Ymd') . '_' . md5( json_encode($data) ) ;
        return $md5 ;
    }

    private $_ROOT  = null ;
    private function mkdir($savepath='') {
        if ( !$this->_ROOT ) {
            $this->_ROOT    = realpath(dirname(__file__).'/../../../public/').'/';
        }


        $dir = rtrim($this->_ROOT.$savepath,'/');
        if (is_dir($dir)) {
            return $dir ;
        }
        if (mkdir($dir, 0755, true)) {
            return $dir ;
        } else {
            $this->log("目录 {$savepath} 创建失败！");
            return false ;
        }
    }

    private function log($msg) {
        // $this->R();
        // if ( is_array( $msg ) ) {
        //     print_r($msg);
        //     $this->redis->LPUSH('log_img',json_encode($msg,JSON_UNESCAPED_UNICODE) );
        // }else{
        //     print_r([$msg]);
        //     $this->redis->LPUSH('log_img',$msg );
        // }
    }

}
